//
//  ZYCustomButton.swift
//  SwiftDemo1
//
//  Created by wzp on 2025/6/1.
//

import Foundation
import UIKit
class ZYImageTopButton: UIButton {
    
    private lazy var badgeLabel: UILabel = {
        let label = UILabel()
        label.backgroundColor = .red
        label.textColor = .white
        label.layer.cornerRadius = 8
        label.textAlignment = .center
        label.font = UIFont.systemFont(ofSize: 8)
        return label
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
        layoutUI()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setupUI()
        layoutUI()
    }
    
    
    override func imageRect(forContentRect contentRect: CGRect) -> CGRect {
        let imageFrame = super.imageRect(forContentRect: contentRect)
        let x: CGFloat = (contentRect.size.width - imageFrame.size.width) / 2
        let y: CGFloat = 5
        return CGRect(x: x, y: y, width: imageFrame.size.width, height: imageFrame.size.height)
    }
    
    override func titleRect(forContentRect contentRect: CGRect) -> CGRect {
        let titleFrame = super.titleRect(forContentRect: contentRect)
        let imageFrame = super.imageRect(forContentRect: contentRect)
        let x: CGFloat = (contentRect.size.width - titleFrame.size.width) / 2
        let y: CGFloat = imageFrame.size.height + 8
        return CGRectMake(x, y, titleFrame.size.width, titleFrame.size.height)
    }
    
    override var isSelected: Bool {
        didSet {
            didSelected()
        }
    }
    
    private func setupUI() {
        adjustsImageWhenHighlighted = false
        adjustsImageWhenDisabled = false
        addSubview(badgeLabel)
        badgeLabel.isHidden = true
    }
    
    private func layoutUI() {
        badgeLabel.snp.makeConstraints { make in
            make.bottom.equalTo(self)
            make.right.equalTo(self)
            make.width.height.equalTo(16)
        }
    }
    
    private func didSelected() {
        badgeLabel.text = "0"
        badgeLabel.isHidden = true
    }
    
    func updateBadgeValue(_ value: String) {
        badgeLabel.text = value
        if let num = Int(value) {
            badgeLabel.isHidden = num == 0
        }
    }
    
    func updateUI(forItem item: IZYTabbarItem) {
        self.setTitle(item.normalTitle, for: .normal)
        self.setTitleColor(item.normalTitleColor, for: .normal)
        self.setImage(item.normalImage, for: .normal)
        
        if let selectedTitle = item.selectTitle,
           let selectedTitleColor = item.selectTitleColor {
            self.setTitle(selectedTitle, for: .selected)
            self.setTitleColor(selectedTitleColor, for: .selected)
        }
        
        if let selectedImage = item.selectImage {
            self.setImage(selectedImage, for: .selected)
        }
        
        if let badgeValue = item.badgeValue {
            updateBadgeValue(badgeValue)
        }
    }
}
